'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { Steps, Upload, Radio, Button, message } from 'antd'
import { UploadOutlined, PlusOutlined, LineChartOutlined, LoadingOutlined, CheckCircleFilled } from '@ant-design/icons'
import upfileImg from '@/public/image/upfileimg.png'
import createConfigImg from '@/public/image/createConfig.png'
import createConfigHighImg from '@/public/image/createConfigHigh.png'
import dataFixImg from '@/public/image/dataFix.png'
import dataFixHighImg from '@/public/image/dataFixHigh.png'
import uploadImg from '@/public/image/uploadImg.png'
import wordImg from '@/public/image/fileicon.png'
import type { UploadFile } from 'antd/es/upload/interface'
import { submitStudyBase } from '@/service/tools'

import styles from './styles.module.css'

const AppDetail: FC = () => {
  const [current, setCurrent] = useState(0)
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [parseStrategy, setParseStrategy] = useState('quick')
  const [segmentStrategy, setSegmentStrategy] = useState('auto')
  const [submitStatus, setSubmitStatus] = useState<'loading' | 'success' | 'error'>('loading')

  const getStepIcon = (step: number) => {
    switch (step) {
      case 0:
        return <img src={upfileImg.src} alt="upload" className={styles['step-icon']} />;
      case 1:
        return <img
          src={current >= 1 ? createConfigHighImg.src : createConfigImg.src}
          alt="config"
          className={styles['step-icon']}
        />;
      case 2:
        return <img
          src={current >= 2 ? dataFixHighImg.src : dataFixImg.src}
          alt="data"
          className={styles['step-icon']}
        />;
      default:
        return null;
    }
  };

  const steps = [
    {
      title: '1上传',
      icon: getStepIcon(0)
    },
    {
      title: '2创建设置',
      icon: getStepIcon(1)
    },
    {
      title: '3数据处理',
      icon: getStepIcon(2)
    }
  ]

  // 处理文件上传
  const handleFileChange = ({ fileList }: { fileList: UploadFile[] }) => {
    setFileList(fileList)
  }

  const handleNext = async () => {
    // 第一步：检查是否有文件
    if (current === 0) {
      if (fileList.length === 0) {
        message.error('请先上传文件')
        return
      }
      setCurrent(current + 1)
    }
    // 第二步：提交处理
    else if (current === 1) {
      try {
        const response = await submitStudyBase({
          user_id: '123456', // 这里使用固定值模拟
          kb_id: 'kb123456', // 这里使用固定值模拟
          kb_file: fileList[0]?.name || '', // 使用上传的文件名
          rule_1: parseStrategy,
          rule_2: segmentStrategy,
        })

        if (response.status === 'true') {
          setSubmitStatus('success')
          setCurrent(current + 1)
        } else {
          setSubmitStatus('error')
          message.error('处理失败，请重试')
        }
      } catch (error) {
        setSubmitStatus('error')
        message.error('处理失败，请重试')
      }
    }
  }

  const handlePrev = () => {
    setCurrent(current - 1)
  }

  const renderProcessingFile = () => {
    if (!fileList[0]) return null;
    const fileName = fileList[0].name;
    const fileSize = fileList[0].size ? `${(fileList[0].size / 1024).toFixed(1)}kb` : '';

    return (
      <div className={styles['file-item']}>
        <div className={styles['file-icon']}>
          <img src={wordImg.src} alt="word" />
        </div>
        <div className={styles['file-info']}>
          <div className={styles['file-name']}>{fileName}</div>
          {fileSize && <div className={styles['file-size']}>{fileSize}</div>}
        </div>
        <div className={styles['file-status']}>
          {submitStatus === 'loading' && <LoadingOutlined className={styles['loading-icon']} />}
          {submitStatus === 'success' && (
            <>
              <CheckCircleFilled className={styles['success-icon']} />
              <span>处理完成</span>
            </>
          )}
        </div>
      </div>
    );
  };

  const renderContent = () => {
    switch (current) {
      case 0:
        return (
          <div className={styles['upload-container']}>
            <Upload
              fileList={fileList}
              onChange={handleFileChange}
              maxCount={1}
              accept=".pdf,.txt,.doc,.docx"
            >
              <div className={styles['upload-area']}>
                <img src={uploadImg.src} alt="upload" className={styles['upload-icon']} />
                <p>点击上传或拖拽文档到这里</p>
                <p className={styles['upload-hint']}>支持 PDF、TXT、DOC、DOCX，最多可上传1个文件，每个文件不超过100MB，PDF最多500页</p>
              </div>
            </Upload>
          </div>
        )
      case 1:
        return (
          <div className={styles['config-container']}>
            <div className={styles.section}>
              <h3>文档解析策略</h3>
              <Radio.Group value={parseStrategy} onChange={e => setParseStrategy(e.target.value)}>
                <Radio.Button value="quick">
                  <span data-desc="不会对文档提取图像、表格等元素，适用于纯文本">快速解析</span>
                </Radio.Button>
                <Radio.Button value="precise" disabled>
                  <span data-desc="将从文档中提取图片、表格等元素，需要耗费更长的时间">精准解析</span>
                </Radio.Button>
              </Radio.Group>
            </div>
            <div className={styles.section}>
              <h3>分段策略</h3>
              <Radio.Group value={segmentStrategy} onChange={e => setSegmentStrategy(e.target.value)}>
                <Radio.Button value="auto">
                  <span data-desc="自动分段与预处理规则">自动分段与清洗</span>
                </Radio.Button>
                <Radio.Button value="custom" disabled>
                  <span data-desc="自定义分段规则、分段长度及预处理规则">自定义</span>
                </Radio.Button>
                <Radio.Button value="hierarchy" disabled>
                  <span data-desc="按照文档层级结构分段，将文档转化为有层级信息的树结构">按层级分段</span>
                </Radio.Button>
              </Radio.Group>
            </div>
          </div>
        )
      case 2:
        return (
          <div className={styles['process-container']}>
            <div className={styles['processing-status']}>
              <h3>{submitStatus === 'loading' ? '服务器处理中' : '处理完成'}</h3>
              {renderProcessingFile()}
            </div>
          </div>
        )
    }
  }

  return (
    <div className={styles['study-base-process-page-container']}>
      <div className={styles['header']}>
        <div className={styles['back-title']}>添加内容</div>
        <div className={styles['header-actions']}>
          {current > 0 && <Button onClick={handlePrev}>上一步</Button>}
          {current < steps.length - 1 && <Button type="primary" onClick={handleNext}>下一步</Button>}
          {current === steps.length - 1 && <Button type="primary">确定</Button>}
        </div>
      </div>
      <Steps
        current={current}
        items={steps}
        className={styles['steps-nav']}
        labelPlacement="vertical"
      />
      <div className={styles['content-container']}>
        {renderContent()}
      </div>
    </div>
  )
}

export default React.memo(AppDetail)
